package cn.tedu.kcircle.attachment.adapter.http;

import cn.tedu.kcircle.attachment.adapter.converter.AttachmentAdapterConverter;

import cn.tedu.kcircle.attachment.repository.model.AttachAddModel;
import cn.tedu.kcircle.attachment.repository.model.AttachLogAddModel;
import cn.tedu.kcircle.attachment.repository.persist.AttachmentRepository;
import cn.tedu.kcircle.attachment.service.AttachmentService;
import cn.tedu.kcircle.attachment.service.bo.UploadRequestBO;
import cn.tedu.kcircle.attachment.service.bo.UploadResultBO;
import cn.tedu.kcircle.common.enums.OperationEventType;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@AllArgsConstructor
public class AttachmentServiceImpl implements AttachmentService {
    private AttachmentRepository attachmentRepository;
    private AttachmentAdapterConverter converter;

    @Override
    public UploadResultBO uploadQuestionImage(UploadRequestBO uploadRequestBO) {
        return finishUpload(uploadRequestBO, OperationEventType.OP_QUESTION_IMAGE_UPLOAD.getType());
    }

    @Override
    public UploadResultBO uploadQuestionVideo(UploadRequestBO uploadRequestBO) {
        return finishUpload(uploadRequestBO, OperationEventType.OP_QUESTION_VIDEO_UPLOAD.getType());
    }

    @Override
    public UploadResultBO uploadArticleImage(UploadRequestBO uploadRequestBO) {
        return finishUpload(uploadRequestBO, OperationEventType.OP_ARTICLE_IMAGE_UPLOAD.getType());
    }

    @Override
    public UploadResultBO uploadArticleVideo(UploadRequestBO uploadRequestBO) {
        return finishUpload(uploadRequestBO, OperationEventType.OP_ARTICLE_VIDEO_UPLOAD.getType());
    }

    private UploadResultBO finishUpload(UploadRequestBO uploadRequestBO, Integer opEventType) {
        UploadResultBO uploadResultBO = this.uploadFile(uploadRequestBO);
        List<AttachAddModel> attachAddModels = converter.bo2Models(uploadRequestBO, uploadResultBO);
        /*数据库写入上传数据*/
        List<Long> attachIds = attachmentRepository.insertBatchAttach(attachAddModels);
        List<AttachLogAddModel> attachLogAddModels = converter.bo2Models(uploadRequestBO, uploadResultBO, opEventType, attachIds);
        /*数据库写入上传日志*/
        List<Long> longs = attachmentRepository.insertBatchAttachLog(attachLogAddModels);
        return uploadResultBO;
    }
    @Override
    public UploadResultBO uploadFile(UploadRequestBO uploadRequestBO){
        List<String> attachFiles = attachmentRepository.uploadBatch(uploadRequestBO.getFileList());
        return converter.bo2BO(uploadRequestBO, attachFiles);
    }
}
